var express = require('express');
var router = express.Router();
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
const QcloudSms = require('qcloudsms_js');
const app = express();
//引入用户数据库
var { LoginModel } = require('../models/zhh.js')
//引入jwt
const jwt = require('jsonwebtoken');
const { randomCode, sendCode } = require("./getMessage");
const { existingEvidenceModel, existingEviTypeModel } = require('../models/zq.js');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

//发送验证码
router.get("/captcha", async (req, res) => {
  //将我们封装好的方法在此进行调用 生成一个四位数的验证码
  let captcha = randomCode(4)
  // 将发送验证码的方法在此调用 这里的第一个参数就是发送验证码的手机号 这个可以从用户输入的信息获取 第二个参数是发送的验证码 第三个参数是一个回调函数 用来判断是否发送成功
  sendCode('17332808337', captcha, function (success) {
    if (success) {
      let token = "Bearer " + jwt.sign({}, "tdy", { expiresIn: '24h' })
      res.send({
        code: 200,
        msg: "发送成功",
        token,
        captcha
      })
    } else {
      res.send({ code: 400, message: '验证码发送失败' })
    }
  })
  // let token = "Bearer " + jwt.sign({}, "secret", { expiresIn: '24h' })
  // res.send({
  //     code: 200,
  //     msg: "发送成功",
  //     token,
  //     captcha
  // })
})


//登录
router.post('/login', async function (req, res) {
  let userName = req.body.username;
  let passWord = req.body.password;
  let data = await LoginModel.findOne({ username: userName, password: passWord });
  console.log(data, 'data');
  if (data) {
    //生成jwt
    const token = "Bearer " + jwt.sign(
      { userName },
      "secret",// secret
      { expiresIn: '1d' } // 过期时间 1天
    );
    let JuddepositEeCount
    let OrdpositEeCount
    let type = await existingEviTypeModel.find()
    console.log(type[0]._id.toString(), type[1]._id.toString());
    if (type[0].name == '司法存证') {
      JuddepositEeCount = await existingEvidenceModel.find({ type: type[0]._id.toString() })
      OrdpositEeCount = await existingEvidenceModel.find({ type: type[1]._id.toString() })
    } else {
      JuddepositEeCount = (await existingEvidenceModel.find({ type: type[1]._id.toString() }))
      OrdpositEeCount = (await existingEvidenceModel.find({ type: type[0]._id.toString() }))
    }
    res.status(200).json({
      code: 200,
      msg: '登录成功',
      token,
      data: {
        username: data.username,
        phone: data.phone,
        CodeId: data.CodeId,
        enterpriseId: data.enterpriseId,
        JuddepositCount: data.Juddeposit,//司法总量
        OrdpositCount: data.Ordposit,//普通总量
        JuddepositEeCount: JuddepositEeCount.length,//司法存证数量
        OrdpositEeCount: OrdpositEeCount.length,//普通存证数量

      }
    });
  } else {
    res.status(300).json({
      code: 300,
      msg: '用户不存在，请注册'
    });
  }
});

//注册
router.post('/enroll', async function (req, res) {
  let userName = req.body.username
  let passWord = req.body.password

  //查找数据库中 是否已经存在当前用户
  let isEnroll = await LoginModel.findOne({ username: userName })
  if (isEnroll) {
    console.log(isEnroll);
    res.send({
      code: 400,
      msg: '用户已存在，请登录'
    })
  } else {
    let data = await LoginModel.create({ username: userName, password: passWord, phone: 17331963869 })
    res.send({
      code: 200,
      msg: '注册成功,请登录',
      data
    })
  }
})

module.exports = router;